import { login, logout, getInfo } from '@/api/user'
import { getUserId, setUserId, removeUserId } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  userid: getUserId(),
  username: '',
  roleid: ''
}

const mutations = {
  SET_USERID: (state, userid) => {
    state.userid = userid
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_ROLE_ID: (state, roleid) => {
    state.roleid = roleid
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { cellphone, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ cellphone: cellphone.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_USERID', data.id)
        setUserId(data.id)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ userid: state.userid }).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        commit('SET_USERNAME', data.username)
        commit('SET_ROLE_ID', data.roleid)

        resolve(data.routers)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.userid).then(() => {
        commit('SET_USERID', '')
        commit('SET_USERNAME', '')
        commit('SET_ROLE_ID', '')

        removeUserId()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetUserId({ commit }) {
    return new Promise(resolve => {
      commit('SET_USERID', '')
      commit('SET_USERNAME', '')

      removeUserId()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

